//
//  CXLNetworkTool+News.m
//  WYNews
//
//  Created by 夜猫子 on 2017/3/19.
//  Copyright © 2017年 夜猫子. All rights reserved.
//

#import "CXLNetworkTool+News.h"
#import "CXLNewListModel.h"

@implementation CXLNetworkTool (News)

/**
 获取网易新闻的列表数据
 
 */
- (void)requestNewList :(NSString *)tib
              callBlock:(void(^)(NSArray *modelArr))callBlock{
    
    NSString *strURL = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/headline/%@/0-20.html", tib];
    
    [[CXLNetworkTool sharedTool] reqeustWith:strURL method:@"GET" parameters:nil callBlock:^(id response) {
        if (response) {
            
            NSArray *dicArr = response[tib];
            NSArray *arr = [NSArray yy_modelArrayWithClass:[CXLNewListModel class] json:dicArr];
            callBlock(arr);
        }else{
            
            callBlock(nil);
            
        }
        
    }];
    

}

/**
 获取网易新闻的详细页的数据
 
 */
- (void)requestDetail:(NSString *)docID
            callBlock:(void(^)(NSString *bodyString))callBlock{
    
    NSString *strURl = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/%@/full.html", docID];
    
    [[CXLNetworkTool sharedTool] reqeustWith:strURl method:@"GET" parameters:nil callBlock:^(id response) {
       
        if (response) {
            
            //详细页的数据的字典
            NSDictionary *bodyDic = response[docID];
            //详细页正文的HTML字符串
            NSString *bodyStr = bodyDic[@"body"];
            
            //正文所有图片
            NSArray *imageArr = bodyDic[@"img"];
            
            //正文的样子,从本地加载
            NSString *css = [NSString stringWithContentsOfURL:[[NSBundle mainBundle]URLForResource:@"news.css" withExtension:nil] encoding:NSUTF8StringEncoding error:NULL];
            
            for (NSDictionary *img in imageArr) {
                
                NSString *imgHteml = [NSString stringWithFormat:@"<img src=%@>",img[@"src"]];
                //把字符串中的相同部分替换
                bodyStr = [bodyStr stringByReplacingOccurrencesOfString:img[@"ref"] withString:imgHteml];
            }
            
            //将CSS与body正文拼接整个数据
            NSString *html = [NSString stringWithFormat:@"%@%@",css,bodyStr];
            //回调
            callBlock(html);
            
        }else{
            callBlock(nil);
        }
        
        
    }];
    
    
    
}

@end
